package controller;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.sun.prism.impl.paint.PaintUtil;
import entity.Price;
import entity.Shopping;
import entity.User;
import entity.User;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import service.ShoppingService;
import utils.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller

public class ShoppingController {
    @Autowired
    private ShoppingService service;

    @RequestMapping("/gouwu")
    public String gouwu() {
        return "shop";
    }

    @RequestMapping("/ymxs")
    public String ymxs() {
        return "single-shop";
    }
    //购物车页面
    @RequestMapping("/getshopping")
    @ResponseBody
    public String getshopping(@RequestParam(value = "sclassification", defaultValue = "0") int sclassification, Model model, HttpServletRequest request) {
        List<Shopping> list = service.getid(sclassification);
        String json = JSON.toJSONString(list);
        return json;
    }
    //根据id查询商品详情
    @RequestMapping("/singleshop")
    public String singleshop(int sid, Model model) {
        Shopping s = service.idcx(sid);
        model.addAttribute("s", s);
        return "single-shop";
    }
    //随即推荐商品
    @RequestMapping("/SuiJTuiJ")
    @ResponseBody
    public String SuiJTuiJ() {
        List<Shopping> list = service.gettuijian();
        String json = JSON.toJSONString(list);
        return json;
    }
    //添加商品至购物车
    @RequestMapping("/addGouWu")
    public String addGouWu(int sid,int pnum, HttpServletRequest request, HttpSession session,Model model){
        Price p=new Price();
        User user2=(User)session.getAttribute("sos");
        p.setPshoppingId(sid);

        p.setPnum(pnum);

        p.setPuserid(user2.getUid());
        int num=0;
        List<Price> list=service.getselect(user2.getUid());
        int a=0;
        for (Price P:list) {
            if(P.getPshoppingId()==sid){
                a=1;
            }
        }
        if(a==1){
            num=service.updel(user2.getUid(),sid,pnum);
        }
        if(a==0){
            num=service.addShopping(p);
        }
       if (num>0){
           return "redirect:/singleshop?sid="+sid;
       }else {
            return "errer";
       }

    }
    //商品显示
    @RequestMapping("ShoppingXS")
    @ResponseBody
    public String ShoppingXS(Model model, HttpSession session){
        User user2=(User)session.getAttribute("sos");
        List<Shopping> list=service.getlist(user2.getUid());
        String json=JSON.toJSONString(list);
        return json;
    }
    //商品删除
    @RequestMapping("del")
    @ResponseBody
    public String del(int pid) {
        int num = service.getdelete(pid);
        String json=JSON.toJSONString(num);
        return json;
    }


    @RequestMapping("list1")
    public String list1(@RequestParam(value = "chaname", defaultValue = "") String chaname,
                        @RequestParam(value = "curPage", defaultValue = "0") Integer curPage,
                        @RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize,
                        Model model) {
        int count = service.listzong(chaname);
        //分类工具对象
        Page<Shopping> page = new Page<Shopping>(curPage, pageSize, count);
        //获得集合
        List<Shopping> list = service.list1(chaname, page.getBeginPos(), pageSize);
        page.setRows(list);
        model.addAttribute("page", page);
        model.addAttribute("count", count);
        model.addAttribute("chaname", chaname);
        return "HT/list";

    }

    @RequestMapping("xiulist")
    public String xiulist(int id,Model model){
        Shopping sh=service.xiulist(id);
        model.addAttribute("sh",sh);
        return "HT/xiu";
    }
    //修改内容
    @RequestMapping(value = "/xiu",produces = {"application/json;charset=UTF-8"})
    public String AddCw(Shopping s,
                        @RequestParam(value = "img1",required = false) MultipartFile[] file1,
                        HttpSession session, HttpServletRequest request){
        String picPath=null;//图片路径
        //判断上传文件是否空
        for (int i=0; i<file1.length ; i++) {
            MultipartFile Mu=file1[i];
            if (!Mu.isEmpty()){
                //获取本地上传路径
                String path=request.getSession().getServletContext().getRealPath("static/img");
                //判断文件格式
                String prefix= FilenameUtils.getExtension(Mu.getOriginalFilename());
                if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")){
                    //构造文件名字
                    String filename=System.currentTimeMillis()+s.getSid()+"."+prefix;
                    File file=new File(path,filename);//文件对象
                    try {
                        Mu.transferTo(file);//将文件写入到文件对象里,执行保存
                        picPath=filename;//保存在数据库中的文件 路径+名字
                    } catch (IOException e) {
                        request.setAttribute("uploadError","上传失败");
                        e.printStackTrace();
                    }
                }else{
                    request.setAttribute("uploadError","图片格式不正确");
                }
            }

        }
       s.setSimg(picPath);
        int num=service.updateByPrimaryKey(s);

        return "redirect:/list1";
    }
    //添加内容
    @RequestMapping(value = "/add1",produces = {"application/json;charset=UTF-8"})
    public String add1(Shopping s,
                        @RequestParam(value = "img1",required = false) MultipartFile[] file1,
                        HttpSession session, HttpServletRequest request){
        String picPath=null;//图片路径
        //判断上传文件是否空
        for (int i=0; i<file1.length ; i++) {
            MultipartFile Mu=file1[i];
            if (!Mu.isEmpty()){
                //获取本地上传路径
                String path=request.getSession().getServletContext().getRealPath("static/img");
                //判断文件格式
                String prefix= FilenameUtils.getExtension(Mu.getOriginalFilename());
                if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")){
                    //构造文件名字
                    String filename=System.currentTimeMillis()+"."+prefix;
                    File file=new File(path,filename);//文件对象
                    try {
                        Mu.transferTo(file);//将文件写入到文件对象里,执行保存
                        picPath=filename;//保存在数据库中的文件 路径+名字
                    } catch (IOException e) {
                        request.setAttribute("uploadError","上传失败");
                        e.printStackTrace();
                    }
                }else{
                    request.setAttribute("uploadError","图片格式不正确");
                }
            }

        }
        s.setSimg(picPath);

        int num=service.insert1(s);

        return "redirect:/list1";
    }

    @RequestMapping("del1")
    public String del1(int sid){//删除

        int num=service.del1(sid);
        if(num==1){
            //成功
            return "redirect:/list1";
        }
        else{
            //失败
            return "redirect:/list1";
        }
    }



}